﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace WorkFlowCore.Conditions
{
    public class ConditionManager
    {
        private IServiceProvider serviceProvider;
        private static object objLock = new object();
        static ConditionManager()
        {
            Allconditions = new List<Condition>();
        }

        public ConditionManager(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }


        /// <summary>
        /// 所有条件
        /// </summary>
        public static List<Condition> Allconditions { get; private set; }
        /// <summary>
        /// 注册条件
        /// </summary>
        /// <param name="conditionId"></param>
        /// <param name="conditionName"></param>
        /// <param name="conditionType"></param>
        /// <param name="description"></param>
        public static void Registercondition(string conditionId, string conditionName, Type conditionType, string description)
        {
            lock (objLock)
            {
                if (Allconditions.Where(s => s.Id == conditionId).Any())
                    return;
                //throw new Exception($"相同的转换器id[{conditionId}]已存在");
            }

            Allconditions.Add(new Condition(conditionId, conditionName, conditionType, description));
        }
        /// <summary>
        /// 从 程序集注册
        /// </summary>
        /// <param name="assemblies"></param>
        public static void Registercondition(params Assembly[] assemblies)
        {
            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes().Where(t => t.GetCustomAttribute<ConditionAttribute>() != null);

                foreach (var type in types)
                {
                    var attr = type.GetCustomAttribute<ConditionAttribute>();
                    var conditionId = type.FullName;
                    var conditionName = attr.Name ?? type.FullName;
                    Registercondition(conditionId, conditionName, type, attr.Description);
                }
            }
        }

        /// <summary>
        /// 获取转换器
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="conditionCreator"></param>
        /// <returns></returns>
        public virtual ICondition GetCondition(string conditionId)
        {

            var condition = Allconditions.FirstOrDefault(s => s.Id == conditionId);
            if (condition == null) return null;
            try
            {
                return (ICondition)serviceProvider.GetService(condition.ConditionType);
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
